import Axios, { AxiosError, AxiosResponse } from 'axios';
import { toast } from 'src/lib/util';
const axiosInstance = Axios.create({
  timeout: 30000,
  timeoutErrorMessage: 'ERR_TIMEOUT'
});

export interface apiResponse {
  status: boolean
  code: number
  message?: string
  data?: Record<string, unknown> | Array<unknown>
}

const onError = (error: unknown): Promise<never> => {
  if (typeof error === 'string') {
    toast('negative', '错误', error)
  } else if ((error as AxiosError).isAxiosError) {
    toast('negative', '错误', (error as AxiosError).message)
  } else {
    toast('negative', '错误', '发生了未知错误。')
  }
  return Promise.reject(error)
}

axiosInstance.interceptors.response.use((value): AxiosResponse<apiResponse> | Promise<never> => {
  if (!value.data) return onError('ERR_UNRESOLVED_RESPONSE');
  const data: apiResponse = value.data as apiResponse;
  if (data.data) return value;
  else return onError(data.message || data.code);
}, onError)
export { axiosInstance };
